layui.use(['upload', 'element'], function () {
    var upload = layui.upload;
    element = layui.element;
    element.init();
    var index;
    upload.render({
        elem: '#btnUpload1',
        url: '/jzApi/utils/fileImprot',
        size: 1024 * 2048,
        // accept:video,
        exts: 'mp4|webm|ogg',
        accept: 'file',
        choose:function(obj){
            //预读本地文件示例，不支持ie8
            layer.load(2);
            obj.preview(function(index, file, result){
                var url = URL.createObjectURL(file);//把file转成URL
                $('#videoattr').attr('src', url); //视频链接
            })},
        done: function (r) {
            layer.close(index);
            $("#enclosure").val(r.data);
            $("#test").html(subFileName(r.data));
            layer.close(layer.index);
            var video_time = document.getElementById("videoattr").duration;//视频时长
            var time_length=Math.ceil(video_time);//转为整型
            $("#videoDuration").val(secondChange(time_length))
        },
        progress: function (e, percent) {
            $("#fileProgress").show();
            console.log(JSON.stringify(e));
            console.log("进度：" + e + '%');
            element.progress('progressBar', e + '%');
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
    upload.render({
        elem: '#btnUpload',
        url: '/jzApi/utils/fileImprotAndToImg',
        timeout: 36000000,
        size: 1024 * 100,
        accept: 'file',
        exts: 'docx|doc|xlsx|ppt|pptx|txt',
        done: function (r) {
            layer.close(index);
            //console.log("r:"+JSON.stringify(r));
            $("#enclosure").val(r.data.url);
            $("#uploadPdfUrl").val(r.data.uploadPdfUrl);
            $("#imgBaseUrl").val(r.data.imgBaseUrl);
            $("#imgName").val(r.data.imgName);
            $("#test").html(subFileName(r.data.url));
        },
        progress: function (e, percent) {
            $("#fileProgress").show();
            console.log(JSON.stringify(e));
            console.log("进度：" + e + '%');
            element.progress('progressBar', e + '%');
            if(e == 100){
                index = layer.load(1, {
                    shade: [0.1,'#fff'] ,//0.1透明度的白色背景
                    content:'请稍候，正在转换文件...',
                    success: function (layerContentStyle) {
                        layerContentStyle.find('.layui-layer-content').css({
                            'padding-top': '35px',
                            'text-align': 'left',
                            'width': '300px'
                        });
                    }
                });
            }
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
    upload.render({
        elem: '#btnUpload2',
        url: '/jzApi/utils/fileImprotAndToImg',
        timeout: 36000000,
        size: 1024 * 100,
        accept: 'file',
        exts: 'pptx|ppt',
        done: function (r) {
            layer.close(index);
            $("#enclosure").val(r.data.url);
            $("#uploadPdfUrl").val(r.data.uploadPdfUrl);
            $("#imgBaseUrl").val(r.data.imgBaseUrl);
            $("#imgName").val(r.data.imgName);
            $("#test").html(subFileName(r.data.url));
        },
        progress: function (e, percent) {
            $("#fileProgress").show();
            console.log(JSON.stringify(e));
            console.log("进度：" + e + '%');
            element.progress('progressBar', e + '%');
            if(e == 100){
                index = layer.load(1, {
                    shade: [0.1,'#fff'] ,//0.1透明度的白色背景
                    content:'请稍候，正在转换文件...',
                    success: function (layerContentStyle) {
                        layerContentStyle.find('.layui-layer-content').css({
                            'padding-top': '35px',
                            'text-align': 'left',
                            'width': '300px'
                        });
                    }
                });
            }
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
    upload.render({
        elem: '#btnUpload4',
        url: '/jzApi/utils/fileImprot',
        timeout: 36000000,
        size: 1024 * 100,
        accept: 'file',
        exts: 'jpg|JPEG|png|gif',
        done: function (r) {
            layer.close(index);
            $("#enclosure").val(r.data);
            $("#test").html(subFileName(r.data));
        },
        progress: function (e, percent) {
            $("#fileProgress").show();
            console.log(JSON.stringify(e));
            console.log("进度：" + e + '%');
            element.progress('progressBar', e + '%');
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
});
function getVie(type) {
    if (type != '') {
        $("#resourse").show();
        if (type == 1) {  //为视频格式
            $("#btnUpload5").hide();
            $("#btnUpload1").show();
            $("#videoLabel").show();
            $("#videoDurationDiv").show();
            $("#btnUpload").hide();
            $("#FileLabel").hide();
            $("#btnUpload2").hide();
            $("#pptLabel").hide();
            $("#btnUpload4").hide();
            $("#picLabel").hide();
        } else if (type == 2) {  //为课件（ppt、pptx）格式
            $("#btnUpload5").hide();
            $("#btnUpload2").show();
            $("#pptLabel").show();
            $("#videoLabel").hide();
            $("#videoDurationDiv").hide();
            $("#btnUpload").hide();
            $("#FileLabel").hide();
            $("#btnUpload1").hide();
            $("#btnUpload4").hide();
            $("#picLabel").hide();
        } else if (type == 4) {  //为图片格式
            $("#btnUpload5").hide();
            $("#btnUpload4").show();
            $("#picLabel").show();
            $("#videoLabel").hide();
            $("#videoDurationDiv").hide();
            $("#btnUpload").hide();
            $("#FileLabel").hide();
            $("#btnUpload1").hide();
            $("#btnUpload2").hide();
            $("#pptLabel").hide();
        } else if (type == 5) {  //为视频链接
            $("#btnUpload5").show();
            $("#btnUpload4").hide();
            $("#picLabel").hide();
            $("#videoLabel").hide();
            $("#videoDurationDiv").hide();
            $("#btnUpload").hide();
            $("#FileLabel").show();
            $("#btnUpload1").hide();
            $("#btnUpload2").hide();
            $("#pptLabel").hide();
        } else {
            $("#btnUpload5").hide();
            $("#btnUpload1").hide();
            $("#videoLabel").hide();
            $("#videoDurationDiv").hide();
            $("#btnUpload").show();
            $("#FileLabel").show();
            $("#btnUpload2").hide();
            $("#pptLabel").hide();
            $("#btnUpload4").hide();
            $("#picLabel").hide();
        }
    } else {
        $("#resourse").hide();
    }
}
// 个位数的话在十位数补0
function formatNumber(n) {
    n = n.toString();
    return n[1] ? n : '0' + n
}
// 秒转为计时器
function secondChange(second) {
    var min=Math.floor(second%3600);
    var secondAfter = formatNumber(Math.floor(second/3600)) + ":" + formatNumber(Math.floor(min/60)) + ":"+ formatNumber(second%60);
    return secondAfter
}
$().ready(function() {
    $("#fileProgress").hide();
    $("#chapterId").val($("#chapterId1").val());
    $("#type").val($("#type1").val());
    $("#fileRoute").val($("#fileRoute1").val());

    getVie($("#type1").val());
    $("#type").change(function () {
        $("#enclosure").val("");
        $("#test").html("");
        $("#videoDuration").val("");
        var type = $(this).val();
        getVie(type)
    });
    $.ajax({
        url: '/jzweb/courses/course',
        success: function (r) {
            console.log("r = ", r);
            var coursesId = $("#coursesId1").val();
            var list = r.data
            var opt = '<option value="">请选择课程</option>';
            for (var i = 0; i < list.length; i++) {
                if (coursesId == list[i].id){
                    opt += '<option selected value="' + list[i].id + '">' + list[i].name + '</option>'
                }else {
                    opt += '<option value="' + list[i].id + '">' + list[i].name + '</option>'
                }
            }
            $("#coursesId").html(opt);
        }
    });

    if ($("#coursesId1").val() != ""){
        $("#chapter").css("display","block");
        $.ajax({
            url: '/jzweb/trainingResources/chapter',
            data:{id:$("#coursesId1").val()},
            success: function (r) {
                var chapterId = $("#chapterId1").val();
                var list = r.data;
                var opt = '<option value="">请选择章节</option>';
                for (var i = 0; i < list.length; i++) {
                    if (chapterId == list[i].id){
                        opt += '<option selected value="' + list[i].id + '">' + list[i].name + '</option>'
                    }else {
                        opt += '<option value="' + list[i].id + '">' + list[i].name + '</option>'
                    }
                }
                $("#chapterId").html(opt);
            }
        });
    }else {
        $("#chapter").css("display","none");
    }


    $("#coursesId").change(function () {
        if ($("#coursesId").val() != ""){
            $("#chapter").css("display","block");
            $.ajax({
                url: '/jzweb/trainingResources/chapter',
                data:{id:$("#coursesId").val()},
                success: function (r) {
                    var list = r.data;
                    var opt = '<option value="">请选择章节</option>';
                    for (var i = 0; i < list.length; i++) {
                        opt += '<option value="' + list[i].id + '">' + list[i].name + '</option>'
                    }
                    $("#chapterId").html(opt);
                }
            });
        }else {
            $("#chapter").css("display","none");
        }
    })
    validateRule();
});

$.validator.setDefaults({
    submitHandler : function() {
        update();
    }
});
function update() {
    let type = $("#type").val();
    if(type == 5){
        let btnUpload5 = $("#btnUpload5").val();
        $("#enclosure").val(btnUpload5);
    }
    $.ajax({
        cache : true,
        type : "POST",
        url : "/jzweb/trainingResources/update",
        data : $('#signupForm').serialize(),// 你的formid
        async : false,
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {
            if (data.code == 0) {
                parent.layer.msg("操作成功");
                parent.reLoad();
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);

            } else {
                parent.layer.alert(data.msg)
            }

        }
    });

}
function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules : {
            coursesId : {
                required : true
            },
            chapterId : {
                required : true
            },
            type : {
                required : true
            },
            fileRoute : {
                required : true
            }
        }
    })
}